//
//  ViewController.m
//  TextNote
//
//  Created by rimi on 16/5/3.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import "BSKNoteViewController.h"
#import "BSKTextView.h"
#import "BSKColorPickerView.h"
@import CoreLocation;
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "UIView+SDAutoLayout.h"
#import "UIImage+BSKImageResize.h"
#import <IQKeyboardManager.h>
#import <AVOSCloud/AVOSCloud.h>
#import "BSKWeatherPicker.h"
#import "BSKNote.h"
#import "UIViewController+BSKToast.h"
#import "BSKTypeSelecter.h"
#import "BSK_WGS84TOGCJ02.h"
#import "AFNetworking.h"

@interface BSKNoteViewController ()<UITextViewDelegate,CLLocationManagerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property(nonatomic,strong) BSKTextView * textView;
@property(nonatomic,strong) UIView * titleView;
@property(nonatomic,strong) UILabel * dateLabel;
@property(nonatomic,strong) UILabel * placeLabel;
@property(nonatomic,strong) UILabel * titleLabel;
//@property(nonatomic,strong) NSMutableArray * PhotosSize;
@property(nonatomic,assign) NSInteger noteType;
@property(nonatomic,assign) NSInteger weatherType;

@property(nonatomic,assign) CGFloat TileHeight;
@property(nonatomic,strong) CLLocationManager * locationManager;
@property(nonatomic,assign) BOOL isSave;
@property(nonatomic,strong) UIButton * saveButton;
@property(nonatomic,strong) UIButton * insertImageButton;
@property(nonatomic,strong) UIButton * setBgColorButton;
@property(nonatomic,strong) UIButton * underLineButton;
@property(nonatomic,strong) UIButton * backButton;
@property(nonatomic,strong) UIButton * textColorButton;
@property(nonatomic,strong) BSKWeatherPicker * weatherPiker;
@end

@implementation BSKNoteViewController

- (instancetype)init
{
	self = [super init];
	if (self) {
		_noteType = 1;
		_isNewNote = YES;
		_isSave = YES;
		_CurentNote = [[BSKNote alloc]init];
	}
	return self;
}


-(void)viewWillAppear:(BOOL)animated{
	[IQKeyboardManager sharedManager].enableAutoToolbar = NO;
	[IQKeyboardManager sharedManager].enable = NO;
}

- (void)viewDidLoad {
	[super viewDidLoad];
	
	self.view.backgroundColor = [UIColor whiteColor];
	self.automaticallyAdjustsScrollViewInsets = NO;
	[self initializeView];
	[self loadData];
	
	//注册键盘监听广播
	NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
	[notificationCenter addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
	[notificationCenter addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
	[notificationCenter addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
	[notificationCenter addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
	
}

-(void)dealloc{
	[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotification object:nil];
	[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotification object:nil];
	[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidShowNotification object:nil];
	[[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
-(void)viewDidAppear:(BOOL)animated{
	if (_isNewNote) {
		[_textView becomeFirstResponder];
	}
}


	
//加载控件
-(void)initializeView{
	
	_titleView = [[UIView alloc]init];
	
	_textView = [[BSKTextView alloc]init];
	
	_placeLabel = [[UILabel alloc]init];
	
	_dateLabel = [[UILabel alloc]init];
	
	_titleLabel = [[UILabel alloc]init];
	
	_backButton = [UIButton buttonWithType:UIButtonTypeCustom];
	[_backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
	[self.view addSubview:_titleView];
	[self.view addSubview:_textView];
	[self.view addSubview:_dateLabel];
	[self.view addSubview:_placeLabel];
	[self.view addSubview:_titleLabel];
	[self.view addSubview:_backButton];
	_titleView.sd_layout
		.topSpaceToView(self.view,0)
		.leftSpaceToView(self.view,0)
		.rightSpaceToView(self.view,0)
	.heightIs(NavigationBarHeight + StatusBarHeight);
	_titleView.backgroundColor  =[BSKTheme curentTheme].themeColor;
	_titleView.layer.shadowColor = [[UIColor blackColor]CGColor];
	_titleView.layer.shadowOffset = CGSizeMake(1, 1);
	_titleView.layer.shadowOpacity=0.6;

	_backButton.sd_layout
		.leftSpaceToView(self.view,5)
		.topSpaceToView(self.view,StatusBarHeight+5)
		.heightIs(NavigationBarHeight - 10)
		.widthEqualToHeight();
    _backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
	[_backButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
	_dateLabel.sd_layout
		.topSpaceToView(self.titleView,10)
		.leftSpaceToView(self.view,10)
		.rightSpaceToView(self.view,10)
		.heightIs(15);
	_dateLabel.textAlignment = NSTextAlignmentLeft;
	_dateLabel.font = [UIFont systemFontOfSize:10];
	
	_placeLabel.sd_layout
		.topSpaceToView(self.dateLabel,5)
		.leftSpaceToView(self.view,10)
		.rightSpaceToView(self.view,10)
		.heightIs(20);
	_placeLabel.text = @"未知地址";
	_placeLabel.textAlignment = NSTextAlignmentLeft;
	_placeLabel.font = [UIFont systemFontOfSize:10];
	_placeLabel.layer.borderColor = [[BSKTheme curentTheme].themeColor CGColor];
	_placeLabel.layer.borderWidth = 1;
	CALayer * masklayer = [CALayer layer];
	masklayer.frame = CGRectMake(1, 1, ScreenWidth-22, 20);
	masklayer.backgroundColor =[[UIColor blueColor] CGColor];
	_placeLabel.layer.mask = masklayer;

	_textView.sd_layout
		.topSpaceToView(_placeLabel,5)
		.leftSpaceToView(self.view,0)
		.rightSpaceToView(self.view,0)
		.bottomSpaceToView(self.view,0);
	_textView.backgroundColor = [UIColor whiteColor];
	_textView.editable =NO;
	
	_textView.textAlignment = NSTextAlignmentLeft;
	_textView.autocorrectionType = UITextAutocorrectionTypeNo;
	_textView.delegate = self;
	
	_titleLabel.sd_layout
		.topSpaceToView(self.view,StatusBarHeight + 10)
		.leftSpaceToView(self.view,40)
		.rightSpaceToView(self.view,40)
		.heightIs(20);
	_titleLabel.textColor = [UIColor whiteColor];
	_titleLabel.font = [UIFont systemFontOfSize:20];
	_titleLabel.textAlignment = NSTextAlignmentCenter;
	
	_toolButton = [UIButton buttonWithType:UIButtonTypeCustom];
	_toolButton.frame=CGRectMake(ScreenWidth-55, ScreenHeight-55, 50, 50);
	
	[_toolButton setImage:[UIImage imageNamed:@"edit"] forState:UIControlStateNormal];
	[_toolButton setImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateSelected];
	_toolButton.imageEdgeInsets = UIEdgeInsetsMake(10,10,10,10);
	_toolButton.backgroundColor = [BSKTheme curentTheme].themeColor;
	_toolButton.layer.cornerRadius = 25;
	
	_toolButton.layer.shadowColor = [[UIColor blackColor] CGColor];
	_toolButton.layer.shadowOffset = CGSizeMake(3,3);
	_toolButton.layer.shadowOpacity = 0.3;
	_toolButton.showsTouchWhenHighlighted =YES;
	[_toolButton addTarget:self action:@selector(toolButtonAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:_toolButton];
	
	_saveButton = [self getToolButtonItemWithImage:@"yes" ActionSelecter:@selector(saveAction:)];
	_insertImageButton = [self getToolButtonItemWithImage:@"picture" ActionSelecter:@selector(insertImageAction:)];
	_setBgColorButton =  [self getToolButtonItemWithImage:@"fontColor_BG" ActionSelecter:@selector(setBgcolorAction:)];
	_underLineButton = [self getToolButtonItemWithImage:@"underline" ActionSelecter:@selector(underLineAction:)];
	_textColorButton = [self getToolButtonItemWithImage:@"fontColor" ActionSelecter:@selector(textcolorAction:)];
	
	_TileHeight = _titleView.height+_dateLabel.height+_placeLabel.height;//头部高度：包含状态栏，标题，时间，地点四个部分
	_weatherPiker = [[BSKWeatherPicker alloc]init];
	_weatherPiker.userInteractionEnabled = NO;
	[self.view addSubview: _weatherPiker];
}
//加载数据


-(void)loadData{
	if (!_isNewNote) {
		
		NSString * noteDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
		NSData * data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",noteDirPath,_CurentNote.noteFileName]];
		NSAttributedString * content =[[NSAttributedString alloc] initWithData:data options:@{NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType} documentAttributes:nil error:nil];
		
		self.dateLabel.text = _CurentNote.date;
		self.placeLabel.text = _CurentNote.address;
		self.titleLabel.text =  _CurentNote.title;
		self.weatherPiker.selectedWeatherType = _CurentNote.weatherType;
		self.textView.attributedText = content;
		
	}else{
		[self.locationManager startUpdatingLocation];
		self.locationManager.delegate = self;
		self.placeLabel.text = @"正在定位...";
		self.textView.editable =YES;
		self.weatherPiker.userInteractionEnabled = YES;
		[self.toolButton setTitle:@"菜单" forState:UIControlStateNormal];
		self.titleLabel.text = @"无标题";
	}
	
	self.dateLabel.text = [BSKNoteViewController getTimeString];
	_CurentNote.date = _dateLabel.text;
}

-(void)viewWillDisappear:(BOOL)animated{
	[self.view endEditing:YES];
}

-(void)viewDidDisappear:(BOOL)animated{
	[IQKeyboardManager sharedManager].enableAutoToolbar = YES;
	[IQKeyboardManager sharedManager].enable = YES;
}


#pragma mark UITextViewDelegate

-(void)textViewDidChange:(UITextView *)textView{
	_isSave = NO;
	NSString * str = [self.textView.attributedText string];
	NSRange range =[str rangeOfString:@"\n"];
	if (range.location!=NSNotFound) {
		self.titleLabel.text =[str substringToIndex:range.location];
	}
	else{
		self.titleLabel.text = str;
	}
	if ([self.titleLabel.text isEqualToString:@""]) {
		self.titleLabel.text = @"无标题";
	}
	if(textView.text.length > 0){
		NSString * endstr = [textView.text substringFromIndex:textView.text.length-1];
		if ([endstr isEqualToString:@"\n"]) {
			[_textView removeAllAttributeInRange:NSMakeRange(textView.text.length - 1, 1)];
		}
	}
	else{
		_textView.text = @" ";
		NSRange range = NSMakeRange(0, 1);
		[_textView removeAllAttributeInRange:range];
		_textView.text = @"";
	}
	_CurentNote.title = _titleLabel.text;
}

#pragma mark 获取当前位置


-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
	[manager stopUpdatingLocation];
	CLLocation * location = locations.firstObject;
		//转换后的coord

	CLLocationCoordinate2D locationCoordinate = [BSK_WGS84TOGCJ02 wgs84ToGcj02:[location coordinate]];
	
	CLGeocoder * coder = [[CLGeocoder alloc]init];
	[coder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
		if (error) {
			NSLog(@"%@",error);
			return ;
		}
		CLPlacemark * place = placemarks.firstObject;
		NSDictionary * addDic = place.addressDictionary;
		self.placeLabel.text = [addDic[@"FormattedAddressLines"] firstObject];
		_CurentNote.latitude = locationCoordinate.latitude;
		_CurentNote.longitude = locationCoordinate.longitude;
	}];
}

#pragma mark 获取当前时间

+ (NSString * )getTimeString{
	NSDate * date = [NSDate date];
	NSDateFormatter * formater = [[NSDateFormatter alloc]init];
	[formater setDateFormat:@"yyy/MM/dd"];
	return [formater stringFromDate:date];
}


#pragma mark 创建按钮菜单
-(UIButton *)getToolButtonItemWithImage:(NSString *)imageName ActionSelecter:(SEL)selecter{
	CGFloat buttonWidth = MIN(ScreenWidth / 6,50);
	UIButton * button;
	button = [UIButton buttonWithType:UIButtonTypeCustom];
	[self.view addSubview:button];
	button.frame=CGRectMake(ScreenWidth-buttonWidth, ScreenHeight-buttonWidth, buttonWidth, buttonWidth);
	button.sd_layout.centerYEqualToView(_toolButton);
	[button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
	button.imageEdgeInsets = UIEdgeInsetsMake(10,10,10,10);
	button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
	button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	CGFloat r=0,g=0,b=0,a=0;
	[[BSKTheme curentTheme].themeColor getRed:&r green:&g blue:&b alpha:&a];
	UIColor * buttonColor = [UIColor colorWithRed:r green:g blue:b alpha:0.6];
	button.backgroundColor = buttonColor;
	button.layer.borderColor = [BSKTheme curentTheme].themeColor.CGColor;
	button.layer.borderWidth= 1;
	button.layer.cornerRadius = 25;
	button.showsTouchWhenHighlighted =YES;
	[button addTarget:self action:selecter forControlEvents:UIControlEventTouchUpInside];
	button.alpha = 0;
	return button;
}

#pragma mark 显示和隐藏菜单

-(void)showButtons{
	CGFloat buttonWidth = ScreenWidth / 6;
	[_toolButton setSelected:YES];
	_saveButton.center = _toolButton.center;
	_insertImageButton.center = _toolButton.center;
	_setBgColorButton.center = _toolButton.center;
	_underLineButton.center = _toolButton.center;
	_textColorButton.center = _toolButton.center;
	[UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		_saveButton.alpha = 1;
		_saveButton.center = CGPointMake(buttonWidth*0.5,_toolButton.center.y);
	} completion:nil];
	
	[UIView animateWithDuration:0.5 delay:0.05 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		_insertImageButton.alpha = 1;
		_insertImageButton.center = CGPointMake(buttonWidth*1.5,_toolButton.center.y);
	} completion:nil];
	
	[UIView animateWithDuration:0.5 delay:0.1 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		_underLineButton.alpha = 1;
		_underLineButton.center = CGPointMake(buttonWidth*2.5,_toolButton.center.y);
	} completion:nil];
	
	[UIView animateWithDuration:0.5 delay:0.15 usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		_setBgColorButton.alpha = 1;
		_setBgColorButton.center = CGPointMake(buttonWidth*3.5,_toolButton.center.y);
	} completion:nil];	[UIView animateWithDuration:0.5 delay:0.2  usingSpringWithDamping:0.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
		_textColorButton.alpha = 1;
		_textColorButton.center = CGPointMake(buttonWidth*4.5,_toolButton.center.y);
	} completion:nil];
	
}


-(void)HideButtons{
	[_toolButton setSelected:NO];
	[UIView animateWithDuration:0.25 animations:^{
		_saveButton.alpha = 0;
		_saveButton.center = _toolButton.center;
		_insertImageButton.alpha = 0;
		_insertImageButton.center = _toolButton.center;
		
		_setBgColorButton.alpha = 0;
		_underLineButton.alpha = 0;
		_textColorButton.alpha = 0;
		
		_setBgColorButton.center = _toolButton.center;
		_underLineButton.center = _toolButton.center;
		_textColorButton.center = _toolButton.center;
	} completion:nil];
}



#pragma mark 按钮菜单事件

-(void)toolButtonAction:(UIButton *)sender{
	if (self.textView.isEditable) {
		if (sender.isSelected) {
			[self HideButtons];
		}else{
			[self showButtons];
		}
	}
	else{
		[sender setTitle:@"菜单" forState:UIControlStateNormal];
		[self.textView setEditable:YES];
		self.weatherPiker.userInteractionEnabled = YES;
		[self.textView becomeFirstResponder];
	}
}

-(void)selectWeatherAction:(UIButton *)sender{
	
}

-(void)saveAction:(UIButton *)sender{
	if (self.textView.attributedText.length == 0) {
		UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有输入任何内容，不能保存" preferredStyle:UIAlertControllerStyleAlert];
		UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
		[alert addAction:cancelAction];
		[self presentViewController:alert animated:YES completion:nil];
		return;
	}
	
	NSAttributedString * atstr = self.textView.attributedText;
	NSData * data = [atstr dataFromRange:NSMakeRange(0, atstr.length) documentAttributes:@{NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType} error:nil];
	NSFileManager * manager = [NSFileManager defaultManager];
	
	NSString * noteDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
	
	NSInteger suntoIndex = 100;
	if (_textView.text.length<=100) {
		suntoIndex = _textView.text.length;
	}
	
	if (_isNewNote) {
		NSString * userid = @"null";
		if ([AVUser currentUser]) {
			userid = [AVUser currentUser].objectId;
		}
		NSTimeInterval createTimeTimeInterval = [NSDate date].timeIntervalSince1970;
		NSInteger Createtime = (NSInteger)(createTimeTimeInterval*100);
		
		_CurentNote.noteFileName = [NSString stringWithFormat:@"%ld.rtfd",(long)Createtime];
		_CurentNote.noteID = [NSString stringWithFormat:@"%ld",(long)Createtime];
		
		if ([self.placeLabel.text isEqualToString: @"正在定位..."]) {
			_CurentNote.address = @"未知位置";
			_CurentNote.latitude = -1;
			_CurentNote.longitude = -1;
		}else{
			_CurentNote.address = self.placeLabel.text;
		}
		_CurentNote.weatherType = _weatherPiker.selectedWeatherType;
		
		__weak typeof(self) weakself = self;
		
		
		BSKTypeSelecter * typeselecter = [[BSKTypeSelecter alloc]initWithTyps:_typelist selectedCallBack:^(NSString *typeID) {
			NSRange range;
			if (weakself.textView.attributedText.length>60) {
				range = NSMakeRange(0, 60);
			}
			else{
				range = NSMakeRange(0, weakself.textView.attributedText.length);
			}
            _CurentNote.isChange = YES;
            _CurentNote.objectID = @"null";
            _CurentNote.updateTime = 0.0;
            _CurentNote.uploadTime = createTimeTimeInterval;
            _CurentNote.userID = userid;
            _CurentNote.typeID = typeID;
            _CurentNote.subcontent = [_textView.text substringToIndex:suntoIndex];
			[_dbManager insertDataToTable:@"note"
                                 Columnns:@[@[@"noteID",		_CurentNote.noteID],
                                            @[@"objectID",		@"null"],//表示当前的日记是否已经同步
                                            @[@"isChange",		[NSNumber numberWithBool:YES]],//表示当前日记是否已经更改
                                            @[@"updateTime",	[NSNumber numberWithDouble:createTimeTimeInterval]],//最后一次更新时间
                                            @[@"userID",		userid],
                                            @[@"typeID",		typeID],
                                            @[@"title",		_CurentNote.title],
                                            @[@"latitude",		[NSNumber numberWithDouble:_CurentNote.latitude]],//经度
                                            @[@"longitude",	[NSNumber numberWithDouble:_CurentNote.longitude]],//纬度
                                            @[@"weatherType",	[NSNumber numberWithInt:_CurentNote.weatherType]],
                                            @[@"date",			_CurentNote.date],
                                            @[@"address",		_CurentNote.address],
                                            @[@"subcontent",	[_textView.text substringToIndex:suntoIndex]],
                                            @[@"noteFileName", _CurentNote.noteFileName]]];
			[weakself.view endEditing:YES];
			[weakself.textView setEditable:NO];
			weakself.weatherPiker.userInteractionEnabled = NO;
			if([manager createFileAtPath:[NSString stringWithFormat:@"%@/%@",noteDirPath,_CurentNote.noteFileName] contents:data attributes:nil]){
				[weakself MakeToast:@"保存成功！" WithTime:2];
				[[NSNotificationCenter defaultCenter]postNotificationName:BSKNoteChangeNotification object:nil];
				_isSave = YES;
				_isNewNote = NO;
                [self updateWithNetStatusAndSettings];
			}else{
				[weakself MakeToast:@"保存失败！" WithTime:2];
			}

		}];
		typeselecter.titleLabel.text = @"保存到";
		[self.view addSubview:typeselecter];
		[self.view endEditing:YES];
		[typeselecter show];
		
	}else{
		NSRange range;
		if (self.textView.attributedText.length>60) {
			range = NSMakeRange(0, 60);
		}
		else{
			range = NSMakeRange(0, self.textView.attributedText.length);
		}
        _CurentNote.weatherType = _weatherPiker.selectedWeatherType;
        NSTimeInterval createTimeTimeInterval = [NSDate date].timeIntervalSince1970;
        _CurentNote.isChange = YES;
        _CurentNote.subcontent = [_textView.text substringToIndex:suntoIndex];
        _CurentNote.updateTime = createTimeTimeInterval;
		[_dbManager updateDataToTable:@"note"
                             Columnns:@[@[@"isChange",	  [NSNumber numberWithBool:YES]],//表示当前日记是否已经更改
                                        @[@"title",		_CurentNote.title],
                                        @[@"weatherType", [NSNumber numberWithInt:_CurentNote.weatherType]],
                                        @[@"date",        _CurentNote.date],
                                        @[@"address",     _CurentNote.address],
                                        @[@"subcontent",  [_textView.text substringToIndex:suntoIndex]],
                                        @[@"updateTime",  [NSNumber numberWithDouble:createTimeTimeInterval]],//最后一次更新时间
                                        ]
                            condition: [NSString stringWithFormat:@"noteID = %@", _CurentNote.noteID]];
		
		[self.view endEditing:YES];
		[self.textView setEditable:NO];
		self.weatherPiker.userInteractionEnabled = NO;
		if ([manager fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",noteDirPath,_CurentNote.noteFileName]]&&
			[manager removeItemAtPath:[NSString stringWithFormat:@"%@/%@",noteDirPath,_CurentNote.noteFileName] error:nil] &&
			[manager createFileAtPath:[NSString stringWithFormat:@"%@/%@",noteDirPath,_CurentNote.noteFileName] contents:data attributes:nil]
			){
			[self MakeToast:@"保存成功！" WithTime:2];
			_isSave = YES;
			[[NSNotificationCenter defaultCenter]postNotificationName:BSKNoteChangeNotification object:nil];
            [self updateWithNetStatusAndSettings];
		}else{
			[self MakeToast:@"保存失败！" WithTime:2];
		}
	}

}

- (void)updateWithNetStatusAndSettings {

}

-(void)insertImageAction:(UIButton * )sender{
	UIAlertController *alertControler = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
	//防止循环引用
	__weak typeof(self) weakSelf = self;
	UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
	UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
		[weakSelf selectAlbum:NO];
	}];
	UIAlertAction *albumAction_edit = [UIAlertAction actionWithTitle:@"相册(裁剪)" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
		[weakSelf selectAlbum:YES];
	}];
	UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
		[weakSelf takePhoto];
	}];
	
	[alertControler addAction:cancelAction];
	[alertControler addAction:albumAction];
	[alertControler addAction:albumAction_edit];
	[alertControler addAction:takePhotoAction];
	[self presentViewController:alertControler animated:YES completion:nil];
}

//相册选择照片
- (void)selectAlbum:(BOOL)allowEdit{
	
	UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
	imagePicker.delegate = self;
	//资源类型
	imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	//是否允许编辑
	imagePicker.allowsEditing = allowEdit;
	[self presentViewController:imagePicker animated:YES completion:nil];
	
}
//拍照
- (void)takePhoto {
	if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		UIAlertController * alertControler = [UIAlertController alertControllerWithTitle:@"错误！无法连接到相机" message:@"请检查您的相关设置或者摄像头" preferredStyle:UIAlertControllerStyleAlert];
		UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleCancel handler:nil];
		[alertControler addAction:cancelAction];
		[self presentViewController:alertControler animated:YES completion:nil];
		return;
	}
	
	UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
	imagePicker.delegate = self;
	//资源类型
	imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
	//是否允许编辑
	imagePicker.allowsEditing = YES;
	
	[self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
	_isSave = NO;
	UIImage * img = nil;
	if (picker.allowsEditing) {
		img = info[UIImagePickerControllerEditedImage];
	}else{
		img =info[UIImagePickerControllerOriginalImage];
	}
	CGSize newSize = img.size;
	if (img.size.width>ScreenWidth-10) {
		newSize.width = ScreenWidth-10;
		newSize.height = img.size.height/img.size.width * (ScreenWidth-10);
	}
	UIImage * image = [self imageResize:img ToSize:newSize];
	NSTextAttachment * imgAttachment = [[NSTextAttachment alloc]init];
	imgAttachment.image = image;
	imgAttachment.bounds = CGRectMake(0, 0, image.size.width, image.size.height);
	NSMutableAttributedString * str = [[NSAttributedString attributedStringWithAttachment:imgAttachment] mutableCopy];
	[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0, str.length)];
	NSMutableAttributedString * mstr =[[NSMutableAttributedString alloc]initWithAttributedString:[self.textView.attributedText copy]];
	
	NSRange range =NSMakeRange(self.textView.selectedRange.location+self.textView.selectedRange.length+1, 0);
	[mstr insertAttributedString:str atIndex:self.textView.selectedRange.location];
	self.textView.attributedText = mstr;
	
	
			[mstr enumerateAttributesInRange:NSMakeRange(0, mstr.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
				if([[attrs allKeys] containsObject:@"NSAttachment"]){
					NSTextAttachment * attachment = [attrs objectForKey:@"NSAttachment"];
					NSLog(@"图片尺寸：%lf,%lf",attachment.bounds.size.width,attachment.bounds.size.height);
				}
			}];
	
	
	
	[picker dismissViewControllerAnimated:YES completion:nil];
	[self.textView becomeFirstResponder];
	self.textView.selectedRange =range;
	[self.textView scrollRangeToVisible:range];
	
}

-(void)setBgcolorAction:(UIButton * )sender{
	
	_isSave = NO;
	__weak typeof (self) weakSelf =self;
	NSRange range = self.textView.selectedRange;
	BSKColorPickerView * colorPicker =[[BSKColorPickerView alloc]initWithFrame:self.view.frame];
	colorPicker.onColorSelected = ^(UIColor * color){
		[weakSelf.textView becomeFirstResponder];
		weakSelf.textView.selectedRange = range;
		[weakSelf showButtons];
		if (color) {
			weakSelf.textView.textBgColor = color;
			[weakSelf.textView textBgColorAction:nil];
		}
	};
	[self.view addSubview: colorPicker];
	[self.view endEditing:YES];
	[colorPicker show];
	
}

-(void)underLineAction:(UIButton * )sender{
	_isSave = NO;
	[self.textView underlineAction];
}

-(void)backAction:(UIButton * )sender{
	
	if (_isSave) {
		[self.navigationController popViewControllerAnimated:YES];
	}
	else{
		[self showAllert:^(UIAlertAction *action) {
			[self.navigationController popViewControllerAnimated:YES];
		}];
	}
	
}

-(void)showAllert:(void (^ __nullable)(UIAlertAction *action))okHandler {
	__weak typeof(self) weakSelf = self;
	UIAlertController * alertControler = [UIAlertController alertControllerWithTitle:@"您还没有保存！" message:@"您确认要退出编辑吗？" preferredStyle:UIAlertControllerStyleAlert];
	UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
		[weakSelf showButtons];
	}];
	UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:okHandler];
	[alertControler addAction:cancelAction];
	[alertControler addAction:OKAction];
	[self presentViewController:alertControler animated:YES completion:nil];
}

-(void)textcolorAction:(UIButton * )sender{
	
	__weak typeof (self) weakSelf =self;
	NSRange range = self.textView.selectedRange;
	BSKColorPickerView * colorPicker =[[BSKColorPickerView alloc]initWithFrame:self.view.frame];
	colorPicker.onColorSelected = ^(UIColor * color){
		_isSave = NO;
		[weakSelf.textView becomeFirstResponder];
		weakSelf.textView.selectedRange = range;
		[weakSelf showButtons];
		if (color) {
			[weakSelf.textView textColorAction:color];
		}
	};
	[self.view addSubview: colorPicker];
	[self.view endEditing:YES];
	[colorPicker show];

}

#pragma mark 键盘显示隐藏监听：

-(void)keyBoardWillHide:(NSNotification *)anotification{
	[self HideButtons];
	[UIView animateWithDuration:0.25 animations:^{
		self.toolButton.frame = CGRectMake(ScreenWidth-55, ScreenHeight-55, 50, 50);
		_textView.frame = CGRectMake(0, _TileHeight, ScreenWidth,ScreenHeight-_TileHeight);
		[_textView setNeedsDisplay];
	} completion:^(BOOL finished) {
		_textView.sd_layout.bottomSpaceToView(self.view,0);
		[_textView updateLayout ];
	}];

}

-(void)keyBoardWillShow:(NSNotification *)anotification{
	
	NSDictionary * infoDic = [anotification userInfo];
	CGSize keybordsize = [[infoDic objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
	[UIView animateWithDuration:0.25 animations:^{
	    self.toolButton.frame = CGRectMake(ScreenWidth-55, ScreenHeight-keybordsize.height-55, 50, 50);
		_textView.frame = CGRectMake(0, _TileHeight, ScreenWidth,ScreenHeight-keybordsize.height-_TileHeight);
		[_textView setNeedsDisplay];
	} completion:^(BOOL finished) {
		_textView.sd_layout.bottomSpaceToView(self.view,keybordsize.height);
		[_textView updateLayout ];
	}];
}


-(void)keyBoardDidHide:(NSNotification *)anotification{
}

-(void)keyBoardDidShow:(NSNotification *)anotification{
	[self showButtons];
}

#pragma mark getter
-(CLLocationManager *)locationManager{
	if (_locationManager) {
		return _locationManager;
	}if (![CLLocationManager locationServicesEnabled]) {
		NSLog(@"定位不可用");
	}
	_locationManager = [[CLLocationManager alloc]init];
	//获取权限
	[_locationManager requestWhenInUseAuthorization];
	//设置定位精度
	_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
	//通知数据变更的位置变化阙值
	_locationManager.distanceFilter = kCLHeadingFilterNone;
	return _locationManager;
}

- (UIImage*)imageResize:(UIImage*)image ToSize:(CGSize)size
{
	UIGraphicsBeginImageContext(size);
	[image drawInRect:CGRectMake(0,0,size.width,size.height)];
	UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}

@end
